import 'dart:io';
import 'package:flutter/services.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class VideoDownloader {
  static const MethodChannel _channel = MethodChannel('com.example.app/photos');

  // 请求权限
  Future<bool> requestPermission() async {
    if (Platform.isIOS) {
      var status = await Permission.storage.request();
      if (!status.isGranted) {
        await openAppSettings();
        return false;
      }
      return status.isGranted;
    }
    return true;
  }

  // 获取临时存储路径
  Future<String> _getTempPath() async {
    final directory = await getTemporaryDirectory();
    return directory.path;
  }

  // 下载视频并保存到相册
  Future<bool> downloadAndSaveVideo(String url, String fileName) async {
    try {
      // 检查权限
      bool hasPermission = await requestPermission();
      if (!hasPermission) {
        throw Exception('没有相册权限');
      }

      // 获取临时路径
      String tempPath = await _getTempPath();
      String fullPath = '$tempPath/$fileName';

      // 下载视频
      Dio dio = Dio();
      await dio.download(
        url,
        fullPath,
        onReceiveProgress: (received, total) {
          if (total != -1) {
            print('下载进度: ${(received / total * 100).toStringAsFixed(0)}%');
          }
        },
      );

      // 保存到相册
      if (Platform.isIOS) {
        final result = await _channel.invokeMethod('saveVideoToAlbum', {
          'path': fullPath,
        });
        // 下载完成后清理临时文件
        await File(fullPath).delete();
        return result as bool;
      }
      return true;
    } catch (e) {
      print('错误: $e');
      return false;
    }
  }
}
